'''
@File    :   schedulerplan.py    
@Contact :   kerici2005@163.com
@License :   (C)Copyright 2021-2023, Hunwei-NLPR-CASIA

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2021/7/16 14:00   Hunwei      1.0         None
'''

import time
import datetime
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from testapp.dataio.dataiofactory import DataIOFactory




class Schedulerplan(object):
    def __init__(self):
        self.sched = BackgroundScheduler()
        self.sched.start()
        self.datafac = DataIOFactory()

    def getsheherData(self, id):
        """
        获取定时任务信息
        """
        return self.datafac.getSchedulerData(id)


    def test_plan_job(self, *args):
        """
        测试计划任务
        """
        # print('Tick! The time is: %s' % datetime.now())
        requests.post(url='http://127.0.0.1:8001/autoplat/planexcute/', json={"planid": args[0]})



    def swagger_job(self):
        """
        swagger任务
        """
        pass

    def addjob(self, id):
        """
        添加任务
        params:id 定时任务id
        return
        """
        isOK, result = self.getsheherData(id)
        if isOK:
            job = result
            simptime = job.schtime.split(' ')
            for i in range(len(simptime)):
               if '*' == simptime[i]:
                   simptime[i] = None
            try:
                arg = eval(job.params)
                self.sched.add_job(self.test_plan_job, 'cron', year=simptime[0], month=simptime[1], day=simptime[2], day_of_week=simptime[3], hour=simptime[4], minute=simptime[5],
                               second=simptime[6], args=arg, id=str(id))
            except Exception as e:
                return False, str(e)
        return True, '添加任务成功'


    def romovejob(self, id):
        """
        移除任务
        params:id 定时任务id
        return
        """
        try:
            self.sched.remove_job(str(id))
            return True, '移除任务成功'
        except Exception as e:
            return False, str(e)

    def add_job(self, id):
        """
        添加任务
        params:id 定时任务id
        return
        """
        return self.addjob(id)

    def romove_job(self, id):
        """
        移除任务
        params:id 定时任务id
        return
        """
        return self.romovejob(id)

# abs = Schedulerplan()
# abs.start()
# # abs.stop()
# while(1):
#     pass